package com.kjc.demo.basic.controller;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping(value = "/redis")
@Slf4j
public class RedisTestDemo {
	
	@Autowired
	private RedisTemplate<String,Object> redisTemplate;
	
	@GetMapping("/setvalue")
	public String setredisvalue(HttpServletRequest request) {
		String key = request.getParameter("key");
		String value = request.getParameter("value");
		log.info("redis");
		redisTemplate.opsForValue().set(key, value);//Redis赋值
		return "success";
	}
	
	@GetMapping("/getvalue")
	public String getValue(HttpServletRequest request) {
		String key = request.getParameter("key");
		log.info("redis");
		Object obj = redisTemplate.opsForValue().get(key);//redis获取值
		return "success"+ String.valueOf(obj);
	}
	
	@GetMapping("/setIfAbsent")
	public String setIfAbsent(HttpServletRequest request) {
		String key = request.getParameter("key");
		String value = request.getParameter("value");
		log.info("redis");
		boolean lock = redisTemplate.opsForValue().setIfAbsent(key, value, 30, TimeUnit.SECONDS);
		return "success"+ String.valueOf(lock);
	}
	
}
